import {PageContainer} from "@ant-design/pro-layout"
import ProTable from "@ant-design/pro-table";
import {connect} from "@@/plugin-dva/exports";
import {useEffect, useState} from "react";
import {PlusOutlined} from "@ant-design/icons";
import {Button, message} from "antd";
import CreateOrEdit from "./components/CreateOrEdit";
import {updatePerson} from "@/services/person/person";





const Person: React.FC = (props) => {

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editId, setEditId] = useState(undefined);

  const {dispatch} = props;

  const {personList} = props.person

  const isShowModal = (show, id = undefined) => {
    setEditId(id);
    setIsModalVisible(show);
  };



  const fresh = () => dispatch({
    type: "person/fetchPersons",
    payload: null
  });

  useEffect(() => {
    dispatch({
      type: "person/fetchPersons",
      payload: null
    });
  },[]);


  // 提交表单，添加
  const createWithForm = (values) => {
    dispatch({
      type: "person/addPerson",
      payload: values,
      callback: (msg)=> {
        fresh();
        message.info(msg)
      }
    })
  };

  const editWithForm = (values,id) => {
    dispatch({
      type: "person/modifyPerson",
      payload: {values, id},
      callback: (msg)=> {
        fresh();
        message.info(msg)
      }
    });
  };

  const CreateOrEditWithForm = (values, id = undefined) => {
    if (id === undefined) {
      createWithForm(values);
    }else {
      editWithForm(values, id);
    }
  };

  const uideleteperson = (id) => {
    dispatch({
      type: "person/removePerson",
      payload: id,
      callback: (msg)=> {
        fresh()
        message.info(msg);
      }
    })
  };

  const columns = [
    {
      title: "Id",
      dataIndex :"id"
    },
    {
      title: "Name",
      dataIndex: "name"
    },
    {
      title: "Password",
      dataIndex: "password"
    },
    {
      title: "Age",
      dataIndex: "age"
    },
    {
      title: "Gender",
      dataIndex: "gender"
    },
    {
      title: 'Action',
      key: 'action',
      sorter: true,
      valueType: 'option',
      render: (_, record) => [
        <a key="delete" onClick={() => uideleteperson(record.id)}>删除</a>,
        <a key="edit" onClick={()=> isShowModal(true,record.id)}>编辑</a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        rowKey="id"
        dataSource={personList}
        toolBarRender={() => [
          <Button key="button" type="primary" icon={<PlusOutlined/>} onClick={() => isShowModal(true)}>新建</Button>
        ]}
      />



      {
        !isModalVisible ? "":
        <CreateOrEdit
          isModalVisible={isModalVisible}
          isShowModal={isShowModal}
          func={CreateOrEditWithForm}
          editId={editId}
        />

      }

    </PageContainer>
  );
};


export default connect(({person}) => ({person}))(Person);
